/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package modulos.recordatorio.vista;

import basedatos.OperacionesBD;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import modulos.recordatorio.modelo.Recordatorio;
import vista.frmPrincipal;
import vista.modelo.Mensaje;
import vista.modelo.OperacionesVarias;

/**
 *
 * @author francisco
 */
public class FrmListaRecordatorios extends javax.swing.JInternalFrame {

    ArrayList<Recordatorio> recordat;

    /**
     * Creates new form FrmListaRecordatorios
     */
    public FrmListaRecordatorios() {
        initComponents();
        OperacionesVarias.cerrarVentanaEscape(this);
        OperacionesVarias.centrar(this);
        this.recordat = OperacionesVarias.recordatorios;
        if (!recordat.isEmpty()) {
            ponerTabla(recordat);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblRecordatorios = new JTable() {
            public boolean isCellEditable(int rowIndex, int vColIndex) {
                return false;
            }
        };
        txtBusquedas = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setClosable(true);
        setTitle("Recordatorios");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/kwrite.png"))); // NOI18N

        tblRecordatorios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tblRecordatorios.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblRecordatoriosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblRecordatorios);

        txtBusquedas.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBusquedasKeyReleased(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/agt_home.png"))); // NOI18N
        jButton1.setText("Cerrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/delete.png"))); // NOI18N
        jButton2.setText("Eliminar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtBusquedas, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 519, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(txtBusquedas, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblRecordatoriosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblRecordatoriosMouseClicked
        if (evt.getClickCount() == 2) {
            int row = tblRecordatorios.getSelectedRow();
            Recordatorio recor = (Recordatorio) recordat.get(row);
            FrmRecordatorio fr = new FrmRecordatorio(recor, row);
            frmPrincipal.dskpPrincipal.add(fr);
            fr.setVisible(true);
        }
    }//GEN-LAST:event_tblRecordatoriosMouseClicked

    private void txtBusquedasKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBusquedasKeyReleased
        refrescaTabla(txtBusquedas.getText());
    }//GEN-LAST:event_txtBusquedasKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int row = tblRecordatorios.getSelectedRow();
        Recordatorio r = (Recordatorio) recordat.get(row);
        try {
            if (OperacionesBD.eliminar(r, r.getIdRecordatorio())) {
                Mensaje.datosEliminados();
                recordat.remove(r);
                ponerTabla(recordat);
            } else {
                Mensaje.datosNoEliminados();
            }
        } catch (Exception ex) {
            Logger.getLogger(FrmListaRecordatorios.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_jButton2ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblRecordatorios;
    private javax.swing.JTextField txtBusquedas;
    // End of variables declaration//GEN-END:variables

    //poner la tabal de eventos
    private void ponerTabla(ArrayList<Recordatorio> rec) {
        DefaultTableModel dtm = new DefaultTableModel() {
            //Este metodo sirve para devolver el tipo de valores en la tabla si devuelve booleanos se pone un checkbox
            @Override
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();//Devuelve un valor de la fila 0 columna c
            }
        };
        dtm.addColumn("Evento");
        dtm.addColumn("Fecha");
        dtm.addColumn("Hora");
        dtm.addColumn("Cumplido");
        for (int i = 0; i < rec.size(); i++) {
            Recordatorio r = (Recordatorio) rec.get(i);
            Calendar c = r.getFechaHora();
//            c.add(Calendar.MINUTE, +r.getRecordar());
            Object[] obj = new Object[4];
            obj[0] = r.getTitulo();
            obj[1] = OperacionesVarias.fechaString(c.getTime());
            obj[2] = c.get(Calendar.HOUR_OF_DAY) + " : " + c.get(Calendar.MINUTE);
            obj[3] = r.isCumplido();
            dtm.addRow(obj);
//            c.add(Calendar.MINUTE, -r.getRecordar());
        }

        tblRecordatorios.setModel(dtm);
        tblRecordatorios.getColumnModel().getColumn(1).setPreferredWidth(65);
        tblRecordatorios.getColumnModel().getColumn(2).setPreferredWidth(15);
        tblRecordatorios.getColumnModel().getColumn(3).setPreferredWidth(15);
        tblRecordatorios.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    }

    private void refrescaTabla(String campo) {
        ArrayList<Recordatorio> recs = new ArrayList<Recordatorio>();
        for (Recordatorio r : recordat) {
            if (r.getTitulo().toLowerCase().contains(campo.toLowerCase())) {
                recs.add(r);
            }
        }
        ponerTabla(recs);
    }
}
